<?php
namespace App\Http\Controllers\Admin\App;

use App\Services\Main\AdService;
use App\Utilities\JiugeForm;
use App\Utilities\Upload;
use Illuminate\Http\Request;

class AdController extends BaseController
{
    /**
     * 资讯
     */

    protected $view = 'admin.app.ad.';//视图前缀
    protected $url = 'ad';//路由前缀
    protected $service;
    protected $formElementArr = [//表单元素
        //array(表单选项,中文名称,name字段名称,表单提示,js验证规则)
//        array(1,'扩展名称','name','扩展名称，2-20字符',1),
        array(5,'广告位','genre','广告位',6),
        array(2,'广告图片','img','图片上传',11),
        array(1,'跳转地址','link','访问链接',0),
    ];
//    protected $fieldShowArr = [
//        'id' => 'ID',
//        'name' => '扩展名称',
//        'icon' => '扩展图标',
//        'url' => '扩展链接',
//        'createTime' => '创建时间',
//    ];

    public function __construct()
    {
        parent::__construct();
        $this->prefix_url = $this->prefix_url.'/'.$this->url;
        $this->service = new AdService();
        view()->share('prefix_url',$this->prefix_url);
        view()->share('jiugeForm',new JiugeForm($this->prefix_url));
    }

    public function index()
    {
        $models = $this->service->getAdminIndex();
        return view($this->view.'index',array(
            'datas' => $models,
        ));
    }

    public function create()
    {
        return view($this->formView.'edit',array(
            'sels' => $this->formElementArr,
            'options' => array(
                'genre' => $this->service->getGenres(),
            ),
        ));
    }

    public function store(Request $request)
    {
        $data = $this->getData($request);
        $this->service->add($data);
        return redirect($this->prefix_url);
    }

    public function edit($id)
    {
        $model = $this->service->getOne($id);
        return view($this->formView.'edit',array(
            'sels' => $this->formElementArr,
            'options' => array(
                'genre' => $this->service->getGenres(),
            ),
            'data' => $model,
        ));
    }

    public function update(Request $request,$id)
    {
        $model = $this->service->getOne($id);
        $data = $this->getData($request);
        if ($data['img'] && $model->img) {
            $imgOld = $model->img;
        }
        $this->service->modify($data,$id);
        if (isset($imgOld)) { unlink(ltrim('/',$imgOld)); }
        return redirect($this->prefix_url);
    }

    public function getData(Request $request)
    {
        $resImg = Upload::uploadImg($request,'img');
        if (!isset($request->img) || $resImg['code']!=0) {
            echo "<script>alert('上传错误！');history.go(-1)</script>"; exit;
        }
        $genre = $request->genre;
        $link = $request->link ? $request->link : '';
        return array(
            'genre' => $genre,
            'img' => $resImg['filePath'],
            'link' => $link,
        );
    }
}
